import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { makeStyles, useTheme } from '@material-ui/core/styles';
import { useMediaQuery, Grid, Typography, Button } from '@material-ui/core';
import { Icon } from 'components/atoms';
import { SectionHeader } from 'components/molecules';
import { Section, CardPricingStandard } from 'components/organisms';
import { Util } from 'utils/util';
import { useHistory } from "react-router-dom";
import { setLoading } from 'redux/actions/LoadingActions';
import { setCallbackError } from 'redux/actions/LoadingActions';
import { useDispatch, useSelector } from 'react-redux';
import { setSubscriptionItem } from 'redux/actions/SearchArtistsAction';
import { callPostApi } from 'utils/networking';


const useStyles = makeStyles(theme => ({
  pagePaddingTop: {
    paddingTop: theme.spacing(3),
    [theme.breakpoints.up('md')]: {
      paddingTop: theme.spacing(5),
    },
  },
  sectionContainer: {
    backgroundColor: theme.palette.primary.dark,
    paddingBottom: theme.spacing(20),
    borderRadius: '0 0 100% 0',
  },
  textWhite: {
    color: 'white',
  },
  fontWeightBold: {
    fontWeight: 'bold',
  },
  pricingContainer: {
    position: 'relative',
    marginTop: theme.spacing(-20),
  },
  sectionNoPaddingTop: {
    paddingTop: 0,
  },
  cardPricing: {
    '& .countup-number__count-wrapper': {
      textAlign: 'left',
      marginBottom: 0,
      fontWeight: 'bold',
    },
  },
}));

const Main = props => {
  const { data, className, ...rest } = props;
  const classes = useStyles();
  const history = useHistory();
  const dispatch = useDispatch();
  const profileData = useSelector((state) => state.auth.profileData)

  const theme = useTheme();
  const isMd = useMediaQuery(theme.breakpoints.up('md'), {
    defaultMatches: true,
  });

  const actionSubscribeItem = item => {
    if (profileData && profileData.id) {
      if (checkSubscribed(item)) {
        dispatch(setLoading(true));

        const params = {
          user_id: profileData.id,
          subscription_item_id: item.id
        };
        callPostApi('subscription/cancel_subscription', params, dispatch, (data) => {
          data.subscription.status = 0;
          dispatch(setCallbackError({
            title: 'Success',
            content: 'Successfully cancelled'
          }));
        })

      } 
      else {
        dispatch(setSubscriptionItem(item))
        history.push(`/subscription`);
      }
    }
    else {
      history.push(`/signin`);
    }
  }

  const checkSubscribed = (item) => {
    if (!profileData || !profileData.id) {
      return false;
    }
    if (!data) {
      return false;
    }
    return data.subscription
      && data.subscription.subscription_item_id == item.id
      && data.subscription.subscription_id
      && data.subscription.status == 1
      && Date.parse(data.subscription.expired_at) > new Date()
  }

  return (
    <div className={className} {...rest}>
      <Section narrow className={classes.pagePaddingTop}>
        <div>
          <SectionHeader
            title={data.title}
            subtitle={data.sub_title}
            titleProps={{
              className: clsx(classes.fontWeightBold),
              variant: 'h2',
            }}
            data-aos="fade-up"
          />
        </div>
      </Section>
      <div>
        <div>
          <Section className={classes.sectionNoPaddingTop}>
            <Grid container spacing={isMd ? 4 : 2}>
              {data.subscription_items.map((item, index) => (
                <Grid item xs={12} md={4} data-aos="fade-up" key={index}>
                  <CardPricingStandard
                    variant="outlined"
                    withShadow={checkSubscribed(item) ? true : false}
                    subscibed={checkSubscribed(item)}
                    title={item.title}
                    liftUp
                    subtitle={item.sub_title}
                    priceComponent={
                      <div>
                        <Typography variant="h3" color="textPrimary">
                          {Util.getCurrencySymbol(data.currency)}{item.price}
                        </Typography>
                        <Typography variant="h5" style={{ 'color': 'green' }}>
                          {item.duration} months
                        </Typography>
                      </div>
                    }
                    features={[item.feature_1, item.feature_2, item.feature_3, item.feature_4, item.feature_5]}
                    featureCheckComponent={
                      <Icon
                        fontIconClass="far fa-check-circle"
                        fontIconColor={theme.palette.primary.main}
                      />
                    }
                    cta={
                      <Button
                        color="primary"
                        variant={item.isHighlighted ? 'contained' : 'outlined'}
                        fullWidth
                        size="large"
                        onClick={e => {
                          e.stopPropagation()
                          actionSubscribeItem(item)
                        }}
                      >
                        {checkSubscribed(item) ? 'Cancel' : 'Subscribe'}
                      </Button>
                    }
                    disclaimer=""
                    className={classes.cardPricing}
                  />
                </Grid>
              ))}
            </Grid>
          </Section>
        </div>
      </div>
    </div>
  );
};

Main.propTypes = {
  /**
   * External classes
   */
  className: PropTypes.string,
  /**
   * data to be rendered
   */
  data: PropTypes.object.isRequired,
};

export default Main;
